import { isValidElement } from 'react';
import { Navigate } from 'react-router-dom';
import { RouteObject } from 'src/interface/route';

const routeFile = import.meta.glob('./routes/**/*.(tsx|ts)', { eager: true });

export const permissionRoute = [] as RouteObject[];
export const basicRoute = [] as RouteObject[];

const analysisFile = () => {
  Object.keys(routeFile).map((item) => {
    const routeList = (routeFile[item] as { default: RouteObject[] }).default;
    if (item.includes('basic')) {
      basicRoute.push(...routeList.map(analysisRoute));
    } else {
      permissionRoute.push(...routeList.map(analysisRoute));
    }
  });
};

const analysisRoute = (routeItem: RouteObject): RouteObject => {
  if (routeItem.redirect) {
    return {
      path: routeItem.path,
      element: <Navigate to={routeItem.redirect}></Navigate>,
    };
  }
  if (isValidElement(routeItem.element)) {
    return {
      path: routeItem.path,
      element: routeItem.element,
      data: routeItem.data,
      children: routeItem.children?.map(analysisRoute),
    };
  }
  return {
    path: routeItem.path,
    element: <Navigate to="/"></Navigate>,
  };
};

const createRoute = () => {
  analysisFile();

  const routeConfig: RouteObject[] = [
    ...basicRoute,
    {
      path: '/:pathMatch(.*)*',
      element: <Navigate to="/error/404" />,
    },
  ];
  return routeConfig;
};

export const routeConfig = createRoute();
